package com.daocao.hua.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.bumptech.glide.Glide;
import com.daocao.hua.R;
import com.daocao.hua.api.Api;
import com.daocao.hua.api.callback.ShareIndexContract;
import com.daocao.hua.api.requestInfo.ShareIndexRequest;
import com.daocao.hua.util.Network;
import com.daocao.hua.util.QRCode;
import com.daocao.hua.util.RxLifeUtil;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.UI;
import com.daocao.hua.view.Dialog;
import com.daocao.hua.view.V19FrameLayout;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class MyQrCodeActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_code)
    TextView txtCode;
    @BindView(R.id.btn_copy_code)
    SuperButton btnCopyCode;
    @BindView(R.id.img_code)
    ImageView imgCode;
    @BindView(R.id.btn_save_qrcode)
    SuperButton btnSaveQrcode;
    @BindView(R.id.btn_copy_qr_link)
    SuperButton btnCopyQrLink;
    private Unbinder unbiner;
    private String url;
    private String inviteCode;
    private boolean isSaveSuccess = false;
    //    private Bitmap qrcodeBitmap;
    private byte[] bitmapBytes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_qrcode);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("我的邀请码");
        getShareIndex();
    }

    public void getShareIndex() {
        loadingDialog.show();
        Api.api_service.getShareInviteLink().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    inviteCode = result.data.invite_code;
                    txtCode.setText(inviteCode);
                    url = result.data.invite_link;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    QRCode.createQRCode(url).compress(Bitmap.CompressFormat.PNG, 100, baos);
                    bitmapBytes = baos.toByteArray();
                    Glide.with(this).load(bitmapBytes).into(imgCode);


                });
    }

    public void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "hmx");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
        ToastUtil.makeText(context, "保存成功").show();
        isSaveSuccess = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bitmapBytes != null) {
            bitmapBytes = null;
        }
        unbiner.unbind();
        unbiner = null;
    }


    private void copyText(String text) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", text);
// 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
        ToastUtil.makeText(this, "复制成功").show();
    }

    @OnClick({R.id.img_code, R.id.btn_back, R.id.btn_copy_code, R.id.btn_save_qrcode, R.id.btn_copy_qr_link})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.img_code:
                if (bitmapBytes != null) {
                    Dialog.showBigQrcodeIcon(this, bitmapBytes);
                }
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_copy_code:
                if (TextUtils.isEmpty(inviteCode)) {
                    getShareIndex();
                    return;
                }
                copyText(inviteCode);
                break;
            case R.id.btn_save_qrcode:
                if (TextUtils.isEmpty(url)) {
                    getShareIndex();
                    return;
                }
                if (isSaveSuccess) {
                    ToastUtil.makeText(this, "已保存成功");
                    return;
                }
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        saveImageToGallery(MyQrCodeActivity.this, QRCode.createQRCode(url));
                    }

                    @Override
                    public void superReject() {

                    }
                }, R.string.camera_storage_card_p, R.string.ask_again, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                break;
            case R.id.btn_copy_qr_link:
                if (TextUtils.isEmpty(url)) {
                    getShareIndex();
                    return;
                }
                copyText(url);
                break;
        }
    }
}
